// src/services/authService.ts

import type { LoginFormData, LoginResponseData, CreateAccountResponseData, CreateAccountPayload, UserProfileResponse, UpdateProfileRequest } from '@/types/types';
import { BASE_URL } from '@/services/apiConfig';  // http://localhost:8000

export async function loginUser(credentials: LoginFormData): Promise<LoginResponseData> {
  try {

    const response = await fetch(`${BASE_URL}/users/login`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(credentials),
    });

    if (!response.ok) {
      throw new Error('Login failed');
    }

    const data: LoginResponseData = await response.json();
    return data;
  } catch (error) {
    console.error('Login request error:', error);
    throw error;
  }
}

export async function createAccount(registerData: CreateAccountPayload): Promise<CreateAccountResponseData> {
  try {
    const response = await fetch(`${BASE_URL}/users/register`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(registerData),
    });

    if (!response.ok) {
      throw new Error('Registration failed');
    }

    const data: CreateAccountResponseData = await response.json();
    return data;
  } catch (error) {
    console.error('Register request error:', error);
    throw error;
  }
}

export async function fetchUserProfile(token: string): Promise<UserProfileResponse> {
  const response = await fetch(`${BASE_URL}/users/me`, {
    method: 'GET',
    headers: {
      Authorization: `Bearer ${token}`,
    },
  });

  if (!response.ok) {
    throw new Error('Failed to fetch user profile');
  }

  const data: UserProfileResponse = await response.json();
  return data;
}

export async function updateUserProfile(data: UpdateProfileRequest, token: string): Promise<unknown> {
  const response = await fetch(`${BASE_URL}/users/profile`, {
    method: 'PUT',
    headers: {
      'Content-Type': 'application/json',
      Authorization: `Bearer ${token}`,
    },
    body: JSON.stringify(data),
  });

  if (!response.ok) {
    throw new Error('Failed to update profile');
  }

  return await response.json();
}

export async function changePassword(
  payload: { old_password: string; new_password: string },
  token: string
): Promise<unknown> {
  const res = await fetch(`${BASE_URL}/users/change-password`, {
    method: 'PUT',
    headers: {
      'Content-Type': 'application/json',
      Authorization: `Bearer ${token}`,
    },
    body: JSON.stringify(payload),
  });

  if (!res.ok) {
    throw new Error('Failed to change password');
  }

  return res.json();
}